﻿using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.Seedwork;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Core.Extension;

namespace Huirui.Cavan.Application.MainBoundedContext.SystemModule
{
    public class CurrencyAppService : BaseAppService<Currency, int, CurrencySearch, ICurrencyRepository>, ICurrencyAppService
    {
       #region IAccountAppService Members

        public override BoolGenericResult<Currency> AddOrUpdate(Currency entity)
        {
            Init();
            BoolGenericResult<Currency> result = new BoolGenericResult<Currency>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            Administrator admin = new Administrator(employee);

            Currency oldCurrency = null;
            if (entity.Id > 0)
            { 
                oldCurrency = this.Repository.Get(entity.Id);
            }
            if (oldCurrency.IsNull())
            {
                oldCurrency = this.GetSingleBySearch(new CurrencySearch() { Code = entity.Code });
                if (oldCurrency.IsNotNull())
                {
                    result.IsSuccess = false;
                    result.Messages.Add("代码需唯一");
                    return result;
                }
                result = admin.AddCurrency(entity.Code, entity.Name, entity.Rate, entity.IsLocal);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = admin.UpdateCurrency(oldCurrency, entity.Name, entity.Rate, entity.IsLocal);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }

        #endregion
    }
}
